<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use app\traits\MyModelTrait;

/**
 * @mixin \think\Model
 */
class UserToken extends Model
{
    use MyModelTrait;

    // 会员登录态
    // 目的：保持单点登录
    protected $table = 'user_token';

    /**
     * 生成记录
     *
     * @param int    $user_id   user.id
     * @param string $token     登录态
     */
    public static function generateLog(int $user_id, string $token): void
    {
        $insert = [
            'user_id'       => $user_id,
            'token'         => $token,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s')
        ];
        self::insert($insert);
    }// generateLog() end

    /**
     * update user_token.token
     *
     * @param int    $user_id   user.id
     * @param string $token
     */
    public static function setToken(int $user_id, string $token): void
    {
        $user = self::whereRaw('user_id = :user_id', ['user_id' => $user_id])->findOrEmpty();
        if ($user->isEmpty())
        {
            self::generateLog($user_id, $token);
        } else {
            $user->token = $token;
            $user->save();
        }
    }// setToken() end
}
